//
//  JXLoginViewController.swift
//  weibo
//
//  Created by admin on 16/5/22.
//  Copyright © 2016年 admin. All rights reserved.
//

import UIKit

import SVProgressHUD

class JXLoginViewController: UIViewController {

	let webView = UIWebView()

	override func viewDidLoad() {
		super.viewDidLoad()

		setLeftBtn()

		loadWebView()

	}

	override func loadView() {

		view = webView

		webView.delegate = self

	}

	// 加载webView,请求授权
	private func loadWebView() {

		let urlString: String = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri

		let url = NSURL(string: urlString)

		let urlRequest = NSURLRequest(URL: url!)

		webView.loadRequest(urlRequest)

	}

	// 设置退出按钮

	private func setLeftBtn() {

		navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "", title: "返回", target: self, action: #selector(goBack))

		// 设置测试按钮
		navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "", title: "测试按钮", target: self, action: #selector(textAccount))

	}

	// 返回
	@objc func goBack() {
        
        SVProgressHUD.dismiss()

		dismissViewControllerAnimated(true, completion: nil)

	}
	// 测试按钮
	@objc func textAccount() {
		// 注入JS
		let jsString = "document.getElementById('userId').value = 'juxin112@foxmail.com',document.getElementById('passwd').value = 'jx112714912521jx' "
		webView.stringByEvaluatingJavaScriptFromString(jsString)

	}

}

//MARK:创建分类,实现代理方法
extension JXLoginViewController: UIWebViewDelegate {

	func webViewDidStartLoad(webView: UIWebView) {
		SVProgressHUD.show()
	}

	func webViewDidFinishLoad(webView: UIWebView) {
		SVProgressHUD.dismiss()

	}

	// 授权成功后回调,代理方法

	func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

		// 请求转为字符串
		let urlString = request.URL?.absoluteString ?? ""

		// 定义授权成功的标记
		let successFlag = "code="

		if urlString.containsString(successFlag) {

			let range = urlString.rangeOfString(successFlag)

			let code = urlString.substringFromIndex((range?.endIndex)!)

			// 请求token值和uid
			JXUserAccountViewModel.shareUserAccount.loadAccessToken(code)

			// 不去加载百度网页
			return false
		}

		return true
	}

}


